package com.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.codesandbox.model.ExecuteCodeRequest;
import com.codesandbox.model.ExecuteCodeResponse;
import com.codesandbox.model.ExecuteMessage;
import com.codesandbox.model.JudgeInfo;
import com.codesandbox.utils.ProcessUtils;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class JavaDockerCodeSandboxOld implements CodeSandbox{
    private static final String GLOBAL_CODE_DIR_NAME="tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME="Main.java";
    private static final long TIME_OUT=5L;
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String language = executeCodeRequest.getLanguage();
        String code = executeCodeRequest.getCode();

        //怎么执行代码-》首先，将code转换为一个java文件-》然后，放到docker容器里-》容器编译java文件-》最后，执行java文件
        //创建存储java文件的文件夹
        //获取工作目录
        String userDir = System.getProperty("user.dir");
        String globalCodePathName=userDir+ File.separator+GLOBAL_CODE_DIR_NAME;
        //判断这个文件夹是否存在，不存在则创建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        //将每个用户的代码分开放
        String userCodeParentPath=globalCodePathName+File.separator+ UUID.randomUUID();
        String userCodePath=userCodeParentPath+File.separator+GLOBAL_JAVA_CLASS_NAME;
        //将code写成java文件
        File Javafile = FileUtil.writeUtf8String(code, userCodePath);
        //编译代码
        //构造编译命令
        String compiledCmd = String.format("javac -encoding utf-8 %s",Javafile.getAbsoluteFile());
        //执行编译命令
        try {
            Process compileProcess = Runtime.getRuntime().exec(compiledCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return getErrorResponse(e);
        }
        //将class文件放到docker里面
        // 设置 Docker 守护进程的地址
        // 生成dockerClient
        DockerClientConfig custom = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("npipe:////./pipe/dockerDesktopLinuxEngine")
                .build();
        // 创建 HTTP 客户端
        DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(custom.getDockerHost())
                .sslConfig(custom.getSSLConfig())
                .build();
        DockerClient dockerClient= DockerClientBuilder.getInstance(custom)
                .withDockerHttpClient(httpClient)
                .build();
        //拉取jdk8
        String image="openjdk:8-alpine";
        // 检查镜像是否存在
        boolean imageExists = true;
        InspectImageResponse inspectImageResponse = null;
        try {
            inspectImageResponse = dockerClient.inspectImageCmd(image).exec();
            System.out.println("该镜像存在");
        } catch (NotFoundException e) {
            //不存在
            imageExists=false;
            System.out.println("该镜像不存在");
        }
        if(!imageExists){
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            try {
                ResultCallback.Adapter<PullResponseItem> pullResponseItemAdapter = pullImageCmd
                        .exec(new PullImageResultCallback() {
                            @Override
                            public void onNext(PullResponseItem item) {
                                System.out.println("下载镜像"+item.getStatus());
                                super.onNext(item);
                            }
                        }).awaitCompletion();
                System.out.println("下载完成");
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
            }
        }
        //创建容器
        CreateContainerCmd containerCmd=dockerClient.createContainerCmd(image);
        HostConfig hostConfig=new HostConfig();
        //映射挂载
        hostConfig.setBinds(new Bind(userCodeParentPath,new Volume("/app")));
        //设置空间
        hostConfig.withMemory(100*1000*1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        CreateContainerResponse createContainerResponse=containerCmd
                .withHostConfig(hostConfig)
                .withAttachStdin(true) //输入
                .withAttachStderr(true) //错误
                .withAttachStdout(true) //输出
                .withTty(true) //交互式容器-》有输入输出
                .withNetworkDisabled(true) //禁用网络
                .withReadonlyRootfs(true) //容器的根文件系统只读
                .exec();
        System.out.println(createContainerResponse);
        //获取容器id
        String containerId = createContainerResponse.getId();
        //启动容器
        dockerClient.startContainerCmd(containerId).exec();
        //在容器中执行代码并获取返回结果
        List<ExecuteMessage> executeMessages=new ArrayList<>();
        //获取占用内存
        final long[] maxMemory = {0L};
        for (String input : inputList) {
            ExecuteMessage executeMessage=new ExecuteMessage();
            //容器执行需要数组，将以前的命令变成数组
            String[] inputs = input.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java","-cp","/app","Main"}, inputs);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令："+execCreateCmdResponse);
            final String[] message = new String[1];
            final String[] errorMessage = new String[1];
            String esecId = execCreateCmdResponse.getId();
            //判断是否超时
            final boolean[] timeout = {true};
            //创建回调函数-》查看输出
            ResultCallback.Adapter<Frame> resultCallbackAdapter = new ResultCallback.Adapter<Frame>() {
                @Override
                public void onComplete() {//完成回调执行的方法，如果完成，说明没超时
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if(StreamType.STDERR.equals(streamType)){
                        errorMessage[0] =new String(frame.getPayload());
                        System.out.println("输出错误结果："+ errorMessage[0]);
                    }else{
                        message[0] =new String(frame.getPayload());
                        System.out.println("输出结果："+ message[0]);
                    }
                    super.onNext(frame);
                }
            };
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void close() throws IOException {

                }

                @Override
                public void onStart(Closeable closeable) {

                }
                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });
            //启动回调函数-》监控内存
            statsCmd.exec(statisticsResultCallback);
            Long time = 0L;
            //启动执行命令
            try {
                StopWatch stopWatch=new StopWatch();
                stopWatch.start();
                dockerClient.execStartCmd(esecId)
                        .exec(resultCallbackAdapter)
                        .awaitCompletion(TIME_OUT, TimeUnit.SECONDS);//设置运行时间，如果超时，则不能执行完毕
                stopWatch.stop();
                time=stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessages.add(executeMessage);
        }
        //构造返回结果
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        //取最大值-》判断是否超时
        long maxTime=0;
        //存结果信息
        List<String> outputList=new ArrayList<>();
        for (ExecuteMessage executeMessage : executeMessages) {
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                //用户提交代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            //存正常信息
            outputList.add(executeMessage.getMessage());
            //找最大的时间
            Long time=executeMessage.getTime();
            if(time!=null){
                maxTime=Math.max(maxTime,time);
            }
        }
        //正常运行完成
        if(outputList.size()==executeMessages.size()){
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOuputList(outputList);
        JudgeInfo judgeInfo=new JudgeInfo();
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory[0]);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        //5.文件清理
        if(Javafile.getParentFile()!=null){
            //直接删除对应的文件夹
            boolean del=FileUtil.del(userCodeParentPath);
            System.out.println("删除"+(del?"成功":"失败"));
        }
        //6.容器清理
        //删除容器
        dockerClient.removeContainerCmd(containerId).withForce(true).exec();
        return executeCodeResponse;
    }
    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse=new ExecuteCodeResponse();
        executeCodeResponse.setOuputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱错误（可能是编译错误）
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
    public static void main(String[] args) {
        JavaDockerCodeSandboxOld javaNativeCodeSandbox = new JavaDockerCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest=new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2","3 4"));
        String code= ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse=javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }
}
